<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../../include/tag.jsp" %>
<style type="text/css">
    .icon-close-new {
        width: 18px;
        height: 18px;
        background-image: url('${ctx}/image/form/create_bg.32.png');
        background-position: -522px 0px;
        position: absolute;
        top: -6px;
        right: -9px;
        cursor: pointer;
    }

    .tag-wrap {
        border: 1px solid #f1eeec;
        min-height: 100px;
        margin-top: 10px;
        padding: 5px;
    }

    .tag-wrap .tag-item {
        float: left;
        margin: 5px 10px 5px 5px;
        padding: 10px;
        background: #fff0f3;
        position: relative;
    }

    .tag-wrap .tag-name {
        line-height: 25px;
        display: inline-block;
        vertical-align: middle;
        float: left;
    }

    .tag-wrap .tag-item.active {
        color: #fff;
        background: #f4615c;
    }

    .tag-wrap:after {
        clear: both;
        content: '';
        display: block;
    }
</style>
<div id="setMemberDialog" style="display: none;">
    <form class="layui-form p10" method="post" action="">
        <div class="layui-form-item select-member-pushall dn">
            <div class="layui-inline">
                <label class="layui-form-label">分配合作商</label>
                <div class="layui-input-block">
                    <input type="radio" name="adminInstitutions" value="1" lay-filter="adminInstitutions"
                           lay-verify="adminInstitutions"
                           title="全部" />
                    <input type="radio" name="adminInstitutions" value="0" lay-filter="adminInstitutions"
                           lay-verify="adminInstitutions"
                           title="单独合作商" />
                </div>
            </div>
        </div>
        <div class="select-member-container dn">
            <a id="selectInitiator" href="javascript:txz.selectInitiatorUtil.selectInitiator(1);" class="layui-btn layui-btn-danger">选择所属者</a>
            <a id="selectPartner" href="javascript:txz.selectInitiatorUtil.selectInitiator(2);" class="layui-btn layui-btn-danger">选择合作商</a>
            <div class="tag-wrap"></div>
        </div>

    </form>
</div>
<script type="text/javascript">
    var form = null;
    $(function () {
        layui.use(['form'], function () {
            form = layui.form;
            form.on('radio(adminInstitutions)', function (data) {
                if (data.value == 0) {
                    //loading层
                    var loadIndex = layer.load(1, {
                        shade: [0.1, '#fff'] //0.1透明度的白色背景
                    });
                    txz.selectInitiatorUtil.getPartnerByInitiator(txz.selectInitiatorUtil.memberId, loadIndex);
                    $(".select-member-container").removeClass("dn");
                    $("[name=adminInstitutions][value='0']").prop('checked', true);
                } else {
                    // 全部合作商
                    $(".select-member-container").find('.tag-wrap').html('');
                    $(".select-member-container").addClass("dn");
                    $("[name=adminInstitutions][value='1']").prop('checked', true);
                }
                form.render('radio');
            });
        });

        txz.selectInitiatorUtil = {
            memberId: null,
            /**
             * 选择管理员
             */
            selectInitiator: function (type) {
                if (type == 1) {
                    openMemberDialog('选择管理员', '${ctx}/system/member/selectMember.do?isAdmin=1', '650px', '700px');
                } else if (type == 2) {
                    openMemberDialog('选择合作商', '${ctx}/system/member/selectMember.do?isPartner=1&multi=1', '950px', '570px');
                }

                function openMemberDialog(title, url, width, height, target) {
                    layer.open({
                        type: 2,
                        area: [width, height],
                        title: title,
                        maxmin: true, //开启最大化最小化按钮
                        content: url,
                        btn: ['确定', '关闭'],
                        yes: function (index, layero) {
                            var body = layer.getChildFrame('body', index);
                            var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                            var inputForm = body.find('#inputForm');
                            var top_iframe;
                            if (target) {
                                top_iframe = target;//如果指定了iframe，则在改frame中跳转
                            } else {
                                top_iframe = '_parent';//获取当前active的tab的iframe
                            }
                            inputForm.attr("target", top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示

                            if (iframeWin.contentWindow.doSubmit()) {
                                var datas = iframeWin.contentWindow.returnData();
                                var _contentArray = new Array();
                                for (var i = 0; i < datas.length; i++) {
                                    var flag = true;
                                    $('#setMemberDialog .tag-wrap').find(".tag-item").each(function (index, ele) {
                                        var itemId = $(ele).data('id');
                                        if (datas[i].id === itemId) {
                                            util.layerMsgError(datas[i].name + '   已存在');
                                            flag = false;
                                        }
                                    })
                                    if (flag) {
                                        _contentArray.push('<div class="tag-item" data-id="' + datas[i].id + '">');
                                        _contentArray.push('<span class="tag-name">' + datas[i].name + '</span>');
                                        _contentArray.push('<span name="event_form_item_ctrl" class="icon-close-new"></span>');
                                        _contentArray.push('</div>');
                                    }
                                    if (!flag) {
                                        return flag;
                                    }
                                }
                                var $content = $('#setMemberDialog .tag-wrap');
                                $content.append(_contentArray.join(""));

                                setTimeout(function () {
                                    top.layer.close(index);
                                }, 100);//延时0.1秒，对应360 7.1版本bug
                            }

                        },
                        cancel: function (index) {
                        }
                    });
                }
            },
            /**
             * 根据合作商编号找对应的所属者
             */
            getMemberByInitiator: function (partnerId, loadIndex) {
                $.post("${ctx}/partner/member/getMemberInitiator.do", {
                    partnerId: partnerId
                }, function (res) {
                    layer.close(loadIndex);
                    var _contentArray = new Array();
                    // 全部
                    for (var i = 0; i < res.data.memberAdmins.length; i++) {
                        _contentArray.push('<div class="tag-item" data-id="' + res.data.memberAdmins[i].id + '">');
                        _contentArray.push('<span class="tag-name">' + res.data.memberAdmins[i].realname + '</span>');
                        _contentArray.push('</div>');
                    }
                    for (var i = 0; i < res.data.members.length; i++) {
                        _contentArray.push('<div class="tag-item" data-id="' + res.data.members[i].id + '">');
                        _contentArray.push('<span class="tag-name">' + res.data.members[i].realname + '</span>');
                        _contentArray.push('<span name="event_form_item_ctrl" class="icon-close-new"></span>');
                        _contentArray.push('</div>');
                    }
                    $(".select-member-pushall").addClass('dn');
                    $("#setMemberDialog .tag-wrap").html(_contentArray.join(""));
                    $(".select-member-container").removeClass("dn");
                })
            },
            getPartnerByInitiator: function (initiatorId, loadIndex, isCheck) {
                $.ajaxSettings.async = false;
                $.post("${ctx}/partner/member/getPartnerByInitiator.do", {
                    initiatorId: initiatorId
                }, function (res) {
                    layer.close(loadIndex);
                    if (res.success) {
                        if (res.data.memberAdmin) {
                            // 全部
                            if (isCheck) {
                                $("[name=adminInstitutions][value='1']").prop('checked', true);
                            }
                            $(".select-member-container").addClass("dn");
                        } else if (res.data.privileges && res.data.privileges.length > 0) {
                            // 单独
                            var _contentArray = new Array();
                            for (var i = 0; i < res.data.privileges.length; i++) {
                                _contentArray.push('<div class="tag-item" data-id="' + res.data.privileges[i].id + '">');
                                _contentArray.push('<span class="tag-name">' + res.data.privileges[i].realname + '</span>');
                                _contentArray.push('<span name="event_form_item_ctrl" class="icon-close-new"></span>');
                                _contentArray.push('</div>');
                            }
                            $("#setMemberDialog .tag-wrap").html(_contentArray.join(""));

                            if (isCheck) {
                                $("[name=adminInstitutions][value='0']").prop('checked', true);
                            }
                            $(".select-member-container").removeClass("dn");
                        } else {
                            $("[name=adminInstitutions][value='0']").prop('checked', false);
                            $("[name=adminInstitutions][value='1']").prop('checked', false);

                            $("#setMemberDialog .tag-wrap").html('');
                            $(".select-member-container").addClass("dn");
                        }
                    }
                    $(".select-member-pushall").removeClass('dn');
                    form.render('radio');
                })
                $.ajaxSettings.async = true;
            },
            openListSetInitiator: function (memberId, type, isCheck) {
                var typeName = type == 1 ? '管理员' : '合作商';
                if (type == 1) {
                    $("#selectPartner").hide();
                } else {
                    $("#selectInitiator").hide();
                }

                txz.selectInitiatorUtil.memberId = memberId;
                //loading层
                var loadIndex = layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });
                var setMemberIndex = layer.open({
                    type: 1,
                    area: ['830px', '380px'],
                    title: '选择' + typeName,
                    content: $("#setMemberDialog"),
                    btn: ['确定', '取消'],
                    success: function () { // 弹出后回调
                        if (type == 1) {
                            txz.selectInitiatorUtil.getMemberByInitiator(memberId, loadIndex)
                        } else {
                            txz.selectInitiatorUtil.getPartnerByInitiator(memberId, loadIndex, isCheck)
                        }
                    },
                    end: function () { // 销毁后回调

                    },
                    yes: function () { // 确定按钮
                        var itemLength = $("#setMemberDialog .tag-wrap").find(".tag-item").length;
                        // if (itemLength == 0) {
                        //     util.layerMsgError("还没有选择" + typeName);
                        //     return false;
                        // }
                        var _memberIds = new Array();
                        $("#setMemberDialog .tag-wrap").find(".tag-item").each(function (index, elem) {
                            _memberIds.push($(elem).data('id'));
                        });
                        var action = null;
                        var params = null;
                        if (type == 1) {
                            action = "${ctx}/partner/member/saveInitiator.do";
                            params = {
                                partnerId: txz.selectInitiatorUtil.memberId,
                                initiatorIds: _memberIds.join(',')
                            }
                        } else {
                            action = "${ctx}/partner/member/savePartner.do";
                            params = {
                                initiatorId: txz.selectInitiatorUtil.memberId,
                                partnerIds: _memberIds.join(','),
                                adminInstitutions: $("[name=adminInstitutions]:checked").val()
                            }
                        }
                        $.post(action, params, function (res) {
                            layer.close(setMemberIndex);
                            if (res.success) {
                                util.layerMsgSuccess('保存成功', function () {
                                    location.reload();
                                });
                            } else {
                                util.layerMsgError('保存失败');
                            }
                        })
                    }
                });
            },
            addEvent: function () {
                $(".tag-wrap").delegate(".icon-close-new", 'click', function (e) {
                    var $target = $(e.target);
                    $target.closest(".tag-item").remove();
                })
            }
        };
        txz.selectInitiatorUtil.addEvent();
    });
</script>